package team.bailan.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import team.bailan.entity.domain.User;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

public class JwtUtil {

    //加密secret
    private static final String SECRET = "doudizhu";
    //过期时间
    private static final Integer TIME_OUT = 60 * 60 * 1000;
    //需要重新生成的天数 如果token的时间超过这个 则重新生成token
    private static final Integer NEED_CREATE_DAY = 7;

    /**
     * 生成token
     * @param user
     * @return
     */
    public static String createToken(User user){
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + TIME_OUT;//一小时有效时间
        Date end = new Date(currentTime);
        return JWT.create()
                .withClaim("userId", user.getId())
                .withClaim("key", DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))
                .withIssuedAt(start)
                .withExpiresAt(end)
                .sign(Algorithm.HMAC256(SECRET));
    }


    /**
     * 获取token信息 如果token有误则返回null
     * @return
     */
    public static DecodedJWT getTokenInfo(){
        try {
            String token = Objects.requireNonNull(getRequest()).getHeader("token");
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 获取用户ID
     * @return
     */
    public static Integer getUserId(){
        DecodedJWT decodedJWT = getTokenInfo();
        assert decodedJWT != null;
        return decodedJWT.getClaim("userId").asInt();
    }


    /**
     * 验证是否修改过密码
     * @param decodedJWT
     * @param user
     * @return
     */
    public static boolean isUpdatedPassword(DecodedJWT decodedJWT,User user){
        String oldPwd = decodedJWT.getClaim("key").asString();
        String newPwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        return !oldPwd.equals(newPwd);
    }

    public static boolean verifyToken(String token){
        DecodedJWT decodedJWT = getTokenInfo();
        return token != null && decodedJWT != null;
    }

    /**
     * 是否需要重新生成token （为了延续token时长）
     * @param decodedJWT
     * @return
     */
    public static boolean needCreate(DecodedJWT decodedJWT){
        /*Date timeoutDate = decodedJWT.getExpiresAt();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,TIME_OUT_DAY - NEED_CREATE_DAY);
        if(timeoutDate.before(calendar.getTime())){
            return true;
        }*/
        return false;
    }

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }

}
